from PyQt5.Qt import *
from resource.query_pane import Ui_Form
from API.API_Tool import APITools
import time


class QueryPane(QWidget, Ui_Form):

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.setupData()

    def setupData(self):
        dic = APITools.get_all_city()
        self.from_station_cb.addItems(dic.keys())
        self.to_station_cb.addItems(dic.keys())
        completer1 = QCompleter(dic.keys())
        completer2 = QCompleter(dic.keys())
        self.from_station_cb.setCompleter(completer1)
        self.to_station_cb.setCompleter(completer2)
        self.start_data.setDate(QDate.currentDate())
        self.start_data.setMinimumDate(QDate.currentDate())
        self.table = QTableWidget()

        model = QStandardItemModel(self.tickets_tv)
        headers = ["车次", "出发站->到达站", "出发时间->到达时间", "历时", "一等座", "二等座", "硬座", "无座"]
        model.setColumnCount(len(headers))
        for idx, title in enumerate(headers):
            model.setHeaderData(idx, Qt.Horizontal, title)
        self.tickets_tv.setModel(model)

    # def setTicket(self):
    #     global ticket_info
    #     ticket_info = "第1次抢票"
    #     self.ticket_count.setText(ticket_info)

    def query_tickets(self):
        print("查询余票")
        dic = APITools.get_all_city()
        start_date = self.start_data.text()
        from_city_code = dic[self.from_station_cb.currentText()]
        to_city_code = dic[self.to_station_cb.currentText()]
        result = APITools.query_ticket(start_date, from_city_code, to_city_code)
        print(result)
        model = self.tickets_tv.model()

        model.setRowCount(len(result))
        columns = ["train_name", ("from_station_name", "to_station_name"), ("start_time", "arrive_time"), "total_time", "first_seat",
         "second_seat", "hard_seat", "no_seat"]
        for row, train_dic in enumerate(result):
            for column, column_name in enumerate(columns):
                if type(column_name) == str:
                    model.setItem(row, column, QStandardItem(train_dic[column_name]))
                else:
                    tmp = "->".join([train_dic[key] for key in column_name])
                    model.setItem(row, column, QStandardItem(tmp))
        self.tickets_tv.setModel(model)
        # APITools.check_user()
        # APITools.submit(train_dic)
        # token, key_check_is_change = APITools.init_dc()
        # passengers = APITools.get_passenger(token)
        # APITools.check_order(passengers, token)
        # APITools.queue_count(train_dic, token)
        # APITools.confirm_queue(passengers, train_dic, token, key_check_is_change)

    def buying_tickets(self):
        # 获取抢票的车次
        dic = APITools.get_all_city()
        row_index = self.tickets_tv.currentIndex().row()
        print(row_index)
        from_city_code = dic[self.from_station_cb.currentText()]
        to_city_code = dic[self.to_station_cb.currentText()]
        start_date = self.start_data.text()
        reverse_city = APITools.get_all_city_reverse()
        params = {
            "leftTicketDTO.train_date": start_date,
            "leftTicketDTO.from_station": from_city_code,
            "leftTicketDTO.to_station": to_city_code,
            "purpose_codes": "ADULT"
        }
        i = 1
        while True:
            ticket_info = "第" + str(i) + "次抢票"
            print(ticket_info)
            self.ticket_count.setText(ticket_info)
            train_dic = APITools.buying_tickets(reverse_city, params, row_index)
            print(train_dic)
            if train_dic is None:
                time.sleep(3)
                i += 1
                QApplication.processEvents()
            else:
                break
        APITools.check_user()
        APITools.submit(train_dic)
        token, key_check_is_change = APITools.init_dc()
        passengers = APITools.get_passenger(token)
        APITools.check_order(passengers, token)
        APITools.queue_count(train_dic, token)
        APITools.confirm_queue(passengers, train_dic, token, key_check_is_change)
        self.ticket_count.setText("恭喜你，已抢到票")
        QApplication.processEvents()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    query = QueryPane()
    query.show()

    sys.exit(app.exec())
